package com.mach.platform.sprider.dev.virdev;

import com.mach.platform.sprider.dev.ByteUtil;
import com.mach.platform.sprider.getter.DataCenter;
import com.mach.platform.sprider.getter.GeneralModbusDev;
import com.mach.platform.sprider.getter.MainWork;
import com.mach.platform.sprider.getter.DataLogService;
import com.mach.platform.util.SqlHelper;
import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.Map;
import java.util.Set;

@Slf4j
public class SimpleSwitchDev extends GeneralModbusDev implements VirDev {



    private SqlHelper sqlHelper;
    private  DataLogService dataLogService;
    private  Map<String, Object> devInfoMap;
//    private  Integer devId;


    public SimpleSwitchDev(Map<String, Object> devInfoMap, SqlHelper sqlHelper, DataLogService dataLogService) throws SQLException {
        super(devInfoMap, sqlHelper, dataLogService);

        this.devInfoMap = devInfoMap;

        this.sqlHelper = sqlHelper;

        this.dataLogService = dataLogService;
    }

    public String getOpenCmdStr(){
        String result = "" + devId +  ":open";

        return result;
    }

    public String getCloseCmdStr(){
        String result = "" + devId +  ":close";

        return result;
    }
    @Override
    protected void pick() {
//        "select dev.id devId, dev.name name,type.prol prol,  dev.dev_type_id devTypeId,\n" +
//                " coll.id collId, coll.name collName, coll.value_addr collAddr,\n " +
//                " dev.comm_addr commAddr,\n" +
//                " coll.data_len collLen, coll.data_type collDataType,\n"；

        Map<Integer, Object> collMap = (Map<Integer, Object>) this.devInfoMap.get("coll");

        Set<Map.Entry<Integer, Object>> collEntrys = collMap.entrySet();

        for(Map.Entry<Integer, Object> collEntry : collEntrys){
            Map<String, Object> coll = (Map<String, Object>) collEntry.getValue();

            Integer devId = (Integer)this.devInfoMap.get("devId");
            String collName = (String)coll.get("collName");
            BigDecimal collAddr = (BigDecimal)coll.get("collAddr");
            Integer collLen = (Integer)coll.get("collLen");
            String collDataType = (String)coll.get("collDataType");
            String collUnit = (String)coll.get("collUnit");
            String prol = (String)this.devInfoMap.get("prol");
            Object result = null;

//            log.info("collName"+ collName);

            try {
                byte[] databuf = null;
                if("SimpleSwitchDevGeneralModbusRTU".equals(prol)){
                    byte[] orgData = this.dh.getDataRtu(collAddr.intValue(), 2);
                   if(orgData == null || orgData.length <1)continue;
                    databuf = ByteUtil.subData(orgData,3,collLen.intValue());
                }else
                if ("SimpleSwitchDevGeneralModbusTCP".equals(prol)){
                    byte[] orgData = this.dh.getDataTcp(collAddr.intValue(), 2);
                   if(orgData == null || orgData.length <1)continue;
                    databuf = ByteUtil.subData(orgData,9,collLen.intValue());
                }

                databuf = ByteUtil.reverse(databuf);
                Short resultInt = ByteUtil.getShort(databuf);
                result = resultInt;

                if( "控制模式".equals(collName) ){

                    if(resultInt == 1){
//                        result = "远程";
                        result = 1;
                    }else if(resultInt == 0){
//                        result = "就地";
                        result = 0;
                    }else{
//                        result = "未知";
                    }

                }

                if( "运行状态".equals(collName) ){
                    if(resultInt == 1){
//                        result = "运行中";
                        result = 1;
                    }else if(resultInt == 0){
//                        result = "停止";
                        result = 0;
                    }else{
//                        result = "未知";
                    }
                }

                if( "故障状态".equals(collName) ){

                    if(resultInt == 1){
//                        result = "故障";
                        result = 1;
                    }else if(resultInt == 0){
//                        result = "正常";
                        result = 0;
                    }else{
//                        result = "未知";
                    }

                }

            }catch (Exception e){
                e.printStackTrace();
                System.err.println("error msg:" + e.getLocalizedMessage() + " devId=" + this.devId + "");
                result = null;
            }

            if(result != null){
                try {

                    MainWork.addResultJustCur(devInfoMap, coll, result);
//                    sqlHelper.updateAsync(
//                            "insert into iot_dev_data_win" +
//                                    "(order_num,dev_id, the_time,data_type,dvalue)" +
//                                    " value(1,"+devId+",now(), '"+collName+"', "+result+")");

                    //this.dataLogService.addDataLogAsync(devId, new Date(), collName, result);

                } catch (Exception e) {
                    e.printStackTrace();
                    System.err.println("error saveToDb... msg:" + e.getLocalizedMessage() + " devId=" + this.devId + "");
                }
            }

        }

    }

    @Override
    public void cmd(Integer cmdLogId,String cmd, String param) {

        try {
            Integer devTypeId = (Integer)this.devInfoMap.get("devTypeId");

            Map<Object, Object> addrMap = sqlHelper.getMapFrTable("name", "valueAddr",
                    "select name, value_addr valueAddr " +
                            " from iot_coll_items colls " +
                            " where colls.dev_type_id=" + devTypeId);

            BigDecimal addr = (BigDecimal)addrMap.get("远程启动与停止");
            Double ctrModelValue = DataCenter.curDevDataTypeValue(this.devId, "控制模式");

            if(ctrModelValue != null && ctrModelValue.equals(1.0)){//远程
//            if(true){//远程
                if("open".equals(cmd) && (null != addr)){
                    this.dh.setDataRtu(addr.intValue(), 1);
                }
                if("close".equals(cmd) && (null != addr)){
                    this.dh.setDataRtu(addr.intValue(), 0);
                }

                sqlHelper.update(
                        "update iot_dev_cmd_log set resp_code=1,resp_ctx='"+EXE_SUCS_CTX+"' where id=" + cmdLogId);

            }else{
                sqlHelper.update(
                        "update iot_dev_cmd_log set resp_code=2,resp_ctx='非远程状态无法控制.' where id=" + cmdLogId);
            }

        } catch (Exception e) {
            e.printStackTrace();
            sqlHelper.updateAsync(
                    "update iot_dev_cmd_log set resp_code=0,resp_ctx='"+e.getLocalizedMessage()+"' where id=" + cmdLogId);
        }finally {
            sqlHelper.updateAsync(
                    "update iot_dev_cmd_log set resp_time=now() where id=" + cmdLogId);
        }




        return;
    }


}
